package handler

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// PaymentRequest 支付请求结构
type PaymentRequest struct {
	AppID       string `json:"appid" binding:"required"`
	MchID       string `json:"mchid" binding:"required"`
	Description string `json:"description" binding:"required"`
	OutTradeNo  string `json:"out_trade_no" binding:"required"`
	Amount      struct {
		Total    int    `json:"total" binding:"required"`
		Currency string `json:"currency" binding:"required"`
	} `json:"amount" binding:"required"`
	Payer struct {
		OpenID string `json:"openid" binding:"required"`
	} `json:"payer" binding:"required"`
	SceneInfo struct {
		PayerClientIP string `json:"payer_client_ip" binding:"required"`
		DeviceID      string `json:"device_id,omitempty"`
		StoreInfo     struct {
			ID       string `json:"id" binding:"required"`
			Name     string `json:"name,omitempty"`
			AreaCode string `json:"area_code,omitempty"`
			Address  string `json:"address,omitempty"`
		} `json:"store_info" binding:"required"`
	} `json:"scene_info" binding:"required"`
	TimeExpire string `json:"time_expire,omitempty"`
	Attach     string `json:"attach,omitempty"`
	GoodsTag   string `json:"goods_tag,omitempty"`
}

// PaymentResponse 支付响应结构
type PaymentResponse struct {
	PrepayID string `json:"prepay_id"`
	ErrCode  int    `json:"errcode"`
	ErrMsg   string `json:"errmsg"`
}

// CloseOrderRequest 关闭订单请求结构
type CloseOrderRequest struct {
	MchID      string `json:"mchid" binding:"required"`
	OutTradeNo string `json:"out_trade_no" binding:"required"`
}

// CloseOrderResponse 关闭订单响应结构
type CloseOrderResponse struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

// QueryOrderRequest 查询订单请求结构
type QueryOrderRequest struct {
	MchID      string `json:"mchid" binding:"required"`
	OutTradeNo string `json:"out_trade_no" binding:"required"`
}

// QueryOrderResponse 查询订单响应结构
type QueryOrderResponse struct {
	MchID          string `json:"mchid"`
	OutTradeNo     string `json:"out_trade_no"`
	TradeState     string `json:"trade_state"`
	TradeStateDesc string `json:"trade_state_desc"`
	Payer          struct {
		OpenID string `json:"openid"`
	} `json:"payer"`
	TransactionID string `json:"transaction_id"`
	Amount        struct {
		Total    int    `json:"total"`
		Currency string `json:"currency"`
	} `json:"amount"`
	SuccessTime string `json:"success_time,omitempty"`
}

// GetSignRequest 获取签名请求结构
type GetSignRequest struct {
	AppID     string `json:"appid" binding:"required"`
	PrepayID  string `json:"prepay_id" binding:"required"`
	SignType  string `json:"sign_type,omitempty"`
	Nonce     string `json:"nonce" binding:"required"`
	Timestamp int64  `json:"timestamp" binding:"required"`
}

// GetSignResponse 获取签名响应结构
type GetSignResponse struct {
	PaySign string `json:"pay_sign"`
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

// CreatePayment 创建支付订单
func CreatePayment(c *gin.Context) {
	var req PaymentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 获取access_token
	accessToken, err := getAccessToken()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取access_token失败"})
		return
	}

	// 构建请求体
	jsonData, err := json.Marshal(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 发送请求到企业微信支付接口
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/miniapppay/create_order?access_token=%s", accessToken)
	fmt.Println(url)
	resp, err := client.Post(url, "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var result PaymentResponse
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// CloseOrder 关闭订单
func CloseOrder(c *gin.Context) {
	var req CloseOrderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 获取access_token
	accessToken, err := getAccessToken()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取access_token失败"})
		return
	}

	// 构建请求体
	jsonData, err := json.Marshal(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 发送请求到企业微信支付接口
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/miniapppay/close_order?access_token=%s", accessToken)
	resp, err := client.Post(url, "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var result CloseOrderResponse
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// QueryOrder 查询订单
func QueryOrder(c *gin.Context) {
	var req QueryOrderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 获取access_token
	accessToken, err := getAccessToken()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取access_token失败"})
		return
	}

	// 构建请求体
	jsonData, err := json.Marshal(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 发送请求到企业微信支付接口
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/miniapppay/get_order?access_token=%s", accessToken)
	resp, err := client.Post(url, "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var result QueryOrderResponse
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// GetSign 获取支付签名
func GetSign(c *gin.Context) {
	var req GetSignRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 获取access_token
	accessToken, err := getAccessToken()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取access_token失败"})
		return
	}

	// 构建请求体
	jsonData, err := json.Marshal(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 发送请求到企业微信支付接口
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/miniapppay/get_sign?access_token=%s", accessToken)
	resp, err := client.Post(url, "application/json", strings.NewReader(string(jsonData)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var result GetSignResponse
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// // 获取access_token
// func getAccessToken() (string, error) {
// 	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
// 		config.GlobalConfig.Wechat.CorpID,
// 		config.GlobalConfig.Wechat.CorpSecret)

// 	resp, err := http.Get(url)
// 	if err != nil {
// 		return "", err
// 	}
// 	defer resp.Body.Close()

// 	body, err := io.ReadAll(resp.Body)
// 	if err != nil {
// 		return "", err
// 	}

// 	var result struct {
// 		ErrCode     int    `json:"errcode"`
// 		ErrMsg      string `json:"errmsg"`
// 		AccessToken string `json:"access_token"`
// 	}

// 	if err := json.Unmarshal(body, &result); err != nil {
// 		return "", err
// 	}

// 	if result.ErrCode != 0 {
// 		return "", fmt.Errorf("获取access_token失败: %s", result.ErrMsg)
// 	}

// 	return result.AccessToken, nil
// }
